package com.trover.myapplication.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.trover.myapplication.core.http.apimodel.Result
import com.trover.myapplication.core.ui.BaseViewModel
import com.trover.myapplication.core.util.CoroutinesDispatcherProvider
import com.trover.myapplication.entity.LoginEntity
import kotlinx.coroutines.launch

class LoginViewModel(
    private val loginRepository: LoginRepository,
    private val provider: CoroutinesDispatcherProvider
) : BaseViewModel() {

    private val _uiState = MutableLiveData<LoginUiState>()
    val uiState: LiveData<LoginUiState>
        get() = _uiState

    fun login(userName: String, password: String) {
        viewModelScope.launch(provider.main) {
            when (val result = loginRepository.login(userName, password)) {
                is Result.Success -> {
                    emitLoginUiState(isSuccess = result.data, isError = "", needLogin = false)
                }
                is Result.Error -> {
                    emitLoginUiState(isError = result.toString(), needLogin = true)
                }
            }
        }
    }

    private fun emitLoginUiState(
        isLoading: Boolean = false,
        isSuccess: LoginEntity? = null,
        isError: String? = null,
        enableLoginButton: Boolean = false,
        needLogin: Boolean = false
    ) {
        val viewModel = LoginUiState(isLoading, isSuccess, isError, enableLoginButton, needLogin)
        _uiState.value = viewModel
    }

    class LoginUiState(
        isLoading: Boolean = false,
        isSuccess: LoginEntity? = null,
        isError: String? = null,
        val enableLoginButton: Boolean = false,
        val needLogin: Boolean = false
    ) :
        BaseViewModel.UiState<LoginEntity>(
            isLoading, false, isSuccess = isSuccess,
            isError = isError
        )
}